package repo

import (
	"time"

	"gitee.com/linxing_3/sr-core/plugins/es"
	"gitee.com/mkwchecking/sr-admin/apps/holoHistMsg/entity"
	"gitee.com/mkwchecking/sr-admin/pkg/http/acl"
	"github.com/olivere/elastic/v7"
)

func NewHistoryMsg(esCli es.IEsClient) *HistoryMsg {
	return &HistoryMsg{
		esCli: esCli,
	}
}

type HistoryMsg struct {
	esCli es.IEsClient
}

func (s *HistoryMsg) GetRoomHistoryMsg(rid string, kw string, startAt, endAt time.Time, page acl.PageReq) ([]*entity.HistoryMsg, int64, error) {

	res := s.esCli.Search(rid).
		// Page(page.PageNum, page.PageSize).
		Sort("holomongomsg.sentTime", false, "long").
		WhereAnd(func(bq *elastic.BoolQuery) {
			if kw != "" {
				bq.Must(elastic.NewMultiMatchQuery("content", "*"+kw+"*"))
			} else {
				bq.Must(elastic.NewMatchAllQuery())
			}

			if !startAt.IsZero() && !endAt.IsZero() && !startAt.After(endAt) {
				bq.Must(elastic.NewRangeQuery("holomongomsg.sentTime").Gte(startAt).Lte(endAt))
			} else if !startAt.IsZero() {
				bq.Must(elastic.NewRangeQuery("holomongomsg.sentTime").Gte(startAt))
			} else if !endAt.IsZero() {
				bq.Must(elastic.NewRangeQuery("holomongomsg.sentTime").Lte(endAt))
			}
		}).
		Do()

	if err := res.Error(); err != nil {
		return nil, 0, err
	}

	msgs := make([]*entity.HistoryMsg, 0)
	err := res.Scan(&msgs)
	return msgs, res.TotalHits(), err
}
